<template>
  <div class="left_tree_area">
    <div class="tree_title">
      <div class="left_title">
        <div class="left_icon">
          <svg-icon :icon-class="iconName"></svg-icon>
        </div>
        <div>{{ title }}</div>
      </div>
      <div class="right_btn">
        <slot name="titleBTn"></slot>
      </div>
    </div>
    <div class="gray_back"></div>
    <!--  去掉了不联动,2-24.12.5 :check-strictly="checkStrictly" -->
    <el-tree
      ref="leftTreeSelectRef"
      v-if="treeData.length > 0"
      :indent="20"
      highlight-current
      class="tree_main"
      :data="treeData"
      :props="treeProps"
      :node-key="nodeKeyField"
      default-expand-all
      :show-checkbox="showCheckbox"
      :default-checked-keys="defaultCheckIds"
      :expand-on-click-node="false"
      @check-change="handleCheckChange"
      @check="handleChecked"
      :check-strictly="checkStrictly"
      @node-click="handleNodeClick"
      :check-on-click-node="canClickToCheck"
    >
      <template #default="{ node, data }">
        <div class="custom-tree-node">
          <div>{{ node.label }}</div>

          <div
            class="right_btn"
            v-if="
              needRightBtn &&
              selectOption[selectProps.value] === data[selectProps.value]
            "
          >
            <!-- v-hasPermi="btn.hasPermis" -->
            <div
              v-for="btn in customButtons"
              :key="btn.title"
              :title="btn.title"
              :class="btn.class"
              @click="btn.action(node, data)"
            >
              <template v-if="shouldShowButton(btn.title, data)">
                <el-icon><component :is="btn.icon" /></el-icon>
              </template>
            </div>
          </div>
        </div>
      </template>
    </el-tree>
  </div>
</template>

<script setup>
const emit = defineEmits(['handleNodeClick', 'handleCheckChange'])
// 接收父组件传递的 props
const props = defineProps({
  title: {
    type: String,
    default: '树形结构',
  },
  iconName: {
    type: String,
    default: 'organizationManagement',
  },
  needRightBtn: {
    //是否需要显示
    type: Boolean,
    default: false,
  },
  //单独控制某个节点的按钮是否显示
  rightBtnCondition: { type: Object, default: () => ({}) }, // 新增：右侧按钮条件控制对象

  treeData: {
    type: Array,
    default: () => [],
    required: true,
  },
  showCheckbox: {
    type: Boolean,
    default: false,
  },
  defaultCheckIds: {
    type: Array,
    default: () => [],
  },
  treeProps: {
    type: Object,
    default: () => ({
      children: 'children',
      label: 'label',
    }),
  },
  nodeKeyField: {
    type: String,
    required: true,
  },
  onNodeClick: {
    type: Function,
    default: () => {},
  },
  customButtons: {
    type: Array,
    default: () => [],
  },
  selectOption: {
    type: Object,
    default: () => {},
  },
  selectProps: {
    type: Object,
    default: () => ({
      children: 'children',
      label: 'Label',
      value: 'value',
    }),
  },
  isCheckStrictly: {
    //父子是否选择关联，只有当进来的时候不关联，选择的时候需要设置为true
    type: Boolean,
    default: false,
  },
})

const canClickToCheck = computed(() => {
  get: {
    return props.showCheckbox ? true : false
  }
  set: (val) => {}
})

// 定义一个可变的ref来存储checkStrictly的状态
const checkStrictly = ref(props.isCheckStrictly)
const leftTreeSelectRef = ref(null)

// 动态判断每个按钮是否应该显示
function shouldShowButton(title, data) {
  // 默认显示所有按钮，如果有 rightBtnCondition 则判断是否存在条件
  return props.rightBtnCondition[title]
    ? props.rightBtnCondition[title](data) // 如果有条件，执行条件函数
    : true // 默认返回 true，显示按钮
}
function handleChecked() {
  console.log(11111, checkStrictly)
  if (checkStrictly.value) {
    nextTick(() => {
      checkStrictly.value = false
    })
  }
}
function handleNodeClick(e) {
  emit('handleNodeClick', e)
}

// 处理节点选择变化
function handleCheckChange(node, checked) {
  const selectedValues = leftTreeSelectRef.value.getCheckedKeys() // 获取被选中的value
  const halfCheckedNodes = leftTreeSelectRef.value.getHalfCheckedNodes() // 获取半选的节点
  // 定义一个函数来递归查找匹配的节点，并在查找时直接过滤 ranks === 0 的节点
  const findNodesByValue = (data, values, filterRanks = false) => {
    let result = []
    data.forEach((item) => {
      // 如果 filterRanks 为 true，则过滤掉 ranks === 0 的节点
      if (values.includes(item.value) && (!filterRanks || item.ranks !== 0)) {
        result.push(item)
      }
      // 递归查找子节点
      if (item.children && item.children.length) {
        result = result.concat(
          findNodesByValue(item.children, values, filterRanks)
        )
      }
    })
    return result
  }

  // 获取选中的节点对象数组
  const selectedNodes = findNodesByValue(props.treeData, selectedValues)

  // 获取并过滤 ranks === 0 的半选节点对象数组
  const halfCheckedNodesArray = findNodesByValue(
    props.treeData,
    halfCheckedNodes.map((node) => node.value),
    true // 传递 true 来开启 ranks 过滤
  )
  // 合并选中的和半选中的节点
  const allSelectedNodes = [...selectedNodes, ...halfCheckedNodesArray]
  // 发射事件，将处理后的节点数据传递给父组件
  emit('handleCheckChange', allSelectedNodes)
}

watch(
  () => props.treeData,
  (newVal) => {
    if (leftTreeSelectRef.value && newVal.length > 0) {
      leftTreeSelectRef.value.setCheckedKeys(props.defaultCheckIds)
    }
  }
)
// 在组件挂载时设置默认选中项
onMounted(() => {
  nextTick(() => {
    if (leftTreeSelectRef.value && props.treeData.length > 0) {
      leftTreeSelectRef.value.setCheckedKeys(props.defaultCheckIds) // 在下一次 DOM 更新后设置选中项
    }
  })
})

defineExpose({
  leftTreeSelectRef,
})
</script>

<style scoped></style>
